package scripting;

import client.MapleClient;
import server.MaplePortal;
import tools.EncodingDetect;
import tools.FilePrinter;

import javax.script.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class PortalScriptManager {
    private static PortalScriptManager instance;
    private Map<String, PortalScript> scripts;
    private static ScriptEngineFactory sef;

    public PortalScriptManager() {
        this.scripts = new HashMap<>();
    }

    public static PortalScriptManager getInstance() {
        return PortalScriptManager.instance;
    }

    private PortalScript getPortalScript(String scriptName) {
        if (this.scripts.containsKey(scriptName)) {
            return (PortalScript) this.scripts.get(scriptName);
        }
        File scriptFile = new File("scripts/portal/" + scriptName + ".js");
        if (!scriptFile.exists()) {
            this.scripts.put(scriptName, null);
            return null;
        }
        InputStream in = null;
        ScriptEngine portal = PortalScriptManager.sef.getScriptEngine();
        try {
            in = new FileInputStream(scriptFile);
            BufferedReader bf = new BufferedReader(new InputStreamReader(in, EncodingDetect.getJavaEncode(scriptFile)));
            CompiledScript compiled = ((Compilable) portal).compile(bf);
            compiled.eval();
        } catch (FileNotFoundException ex) {
        } catch (UnsupportedEncodingException ex2) {
        } catch (ScriptException e) {
            System.err.println("Error executing Portalscript: " + scriptName + ":" + e);
            FilePrinter.printError("PortalScriptManager.txt", (Throwable) e);
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex3) {
            }
        }
        PortalScript script = (PortalScript) ((Invocable) portal).getInterface(PortalScript.class);
        this.scripts.put(scriptName, script);
        return script;
    }

    public void executePortalScript(MaplePortal portal, MapleClient c) {
        PortalScript script = this.getPortalScript(portal.getScriptName());
        if (c != null && c.getPlayer() != null && c.getPlayer().hasGmLevel(2)) {
            c.getPlayer().dropMessage("您已经建立与传送门脚本: " + portal.getScriptName() + ".js 的关联。");
        }
        if (script != null) {
            try {
                script.enter(new PortalPlayerInteraction(c, portal));
            } catch (Exception e) {
                System.err.println("进入传送脚本失败: " + portal.getScriptName() + ":" + e);
            }
        }
        this.clearScripts();
    }

    public void clearScripts() {
        this.scripts.clear();
    }

    static {
        instance = new PortalScriptManager();
        sef = new ScriptEngineManager().getEngineByName("graal.js").getFactory();
    }
}
